package com.lei.demo.dao;

import com.lei.demo.entity.TripForm;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by Shinelon on 2017/6/14.
 */
@Repository
@Transactional
public class TripFormDAO {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    public List<TripForm> getAllTripForms() {
        String hsql = "from tripform";
        Session session = getCurrentSession();
        Query query = session.createQuery(hsql);
        return query.list();
    }

    public void save(TripForm tripForm) {
        Session session = getCurrentSession();
        session.save(tripForm);
    }

    public void update(TripForm tripForm) {
        Session session = getCurrentSession();
        session.update(tripForm);
    }

    public void delete(int trid) {
        Session session = getCurrentSession();
        session.delete(findById(trid));
    }


    public TripForm findById(int trid) {
        Session session = getCurrentSession();
        return (TripForm) session.get(TripForm.class,trid);
    }

    public List<TripForm> findTripForm(String username) {
        return findByCriteria(Restrictions.like("username",username, MatchMode.START));
    }

    public List<TripForm> findTripForm(int trid) {
        return findByCriteria(Restrictions.eq("trid",trid));
    }

    public List<TripForm> findTripFormAll(int trid) {
        return findByCriteria(Restrictions.isNotNull("trid"));

    }

    public List<TripForm> findByCriteria (Criterion criterion){
        Criteria criteria = getCurrentSession().createCriteria(TripForm.class);
        criteria.add(criterion);
        return criteria.list();
    }

}
